package com.lz.learning;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;


public class LeetcodeTraining {


    public static void main(String[] args) {
        LeetcodeTraining  leetcodeTraining =new LeetcodeTraining();

        leetcodeTraining.orangesRotting(new int[][]{{2, 1, 1}, {1, 1, 0}, {0, 1, 1}});

    }


    /**
     * 橘子腐烂传播问题
     */
    int rot;
    int max;
    int flag;

    Map<Integer, Integer> depth = new HashMap();
    LinkedList<Integer> rotted = new LinkedList<>();

    public int orangesRotting(int[][] grid) {
        int length = grid[0].length;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < length; j++) {
                if (grid[i][j] == 2) {
                    int e = i * length + j;
                    depth.put(e, 0);
                    // 通过加法表示两位数，
                    rotted.add(e);

                } else if (grid[i][j] == 1) flag++;
            }
        }
        int size = rotted.size();
        while (size > 0 && flag > 0) {
            rot = rotted.removeFirst();
            int x = rot / length;
            int y = rot % length;

            addPair(x, y - 1, grid);
            addPair(x, y + 1, grid);
            addPair(x - 1, y, grid);
            addPair(x + 1, y, grid);

            size--;
            if (size == 0) {
                size = rotted.size();
            }

        }
        // if (flag == 0) return max;
        if (flag > 0) return -1;
        return max;
    }

    boolean bound(int x, int y, int[][] grid) {
        return x < 0 || x >= grid.length || y < 0 || y >= grid[x].length;
    }

    void addPair(int x, int y, int[][] grid) {
        boolean b = !(x < 0 || x >= grid.length || y < 0 || y >= grid[x].length) && grid[x][y] == 1;
        if (b) {

            Integer e = x * grid[x].length + y;
            rotted.add(e);
            Integer depthInt = depth.get(rot) + 1;
            depth.put(e, depthInt);
            max = depthInt;
            grid[x][y] = 2;
            flag--;
        }
    }



}
